package com.example.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.example.exam.mapper.TUserMapper;
import com.example.exam.pojo.Enum.UserStatusEnum;
import com.example.exam.pojo.entity.TUser;
import com.example.exam.pojo.vo.UserVO.*;
import com.example.exam.service.IAuthenticationService;
import com.example.exam.service.IUserService;
import com.example.exam.service.impl.PwdToolsServiceIpml;
import com.example.exam.tools.JsonResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author LENOVO
 * @description TODO
 * @date 2023/2/3 17:37
 */
@RestController
@RequestMapping("/api/admin/user")
public class UserController {


      @Autowired
      private IUserService userService;

      @Autowired
      private TUserMapper tUserMapper;

      @Autowired
      private  PwdToolsServiceIpml pwdToolsServiceIpml;
      @Autowired
      private IAuthenticationService authenticationService;

    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public JsonResult<PageInfo<TUser>> pageList(@RequestBody UserPageVO model) {
        PageInfo<TUser> pageInfo = userService.userPage(model);

        return  JsonResult.ok(pageInfo);
    }
   @RequestMapping(value = "/current", method = RequestMethod.POST)
    public JsonResult<CurrentVO> current(HttpServletRequest request) {
       TUser user = (TUser) request.getSession().getAttribute("tUser");
       CurrentVO currentVO = new CurrentVO();
       currentVO.setRealName(user.getRealName());
       currentVO.setRole(user.getRole().toString());
       currentVO.setPhone(user.getPhone());
       currentVO.setCreateTime(user.getCreateTime().toString());
       return JsonResult.ok(currentVO);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResult update(@RequestBody @Valid UserUpdateVO model,HttpServletRequest request) {
        TUser user = (TUser) request.getSession().getAttribute("tUser");
        String realName = user.getRealName();
        LambdaQueryWrapper<TUser>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(TUser::getRealName,realName);
        TUser user1 = tUserMapper.selectOne(queryWrapper);
        user1.setModifyTime(new Date());
        userService.updateByIdFilter(user1);
        return JsonResult.ok();
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public JsonResult<UserResponseVO> select(@PathVariable Integer id) {
        TUser user = userService.getUserById(id);
        UserResponseVO userResponseVO=new UserResponseVO();
        BeanUtils.copyProperties(user,userResponseVO);
      //她为什么要使用这种方式来进行数据的转化和矫正呢，因为她将矫正数据的步骤放到了vo一层
        //    UserResponseVM userVm = UserResponseVM.from(user);
        return JsonResult.ok(userResponseVO);
    }


    @RequestMapping(value = "/edit")
    public JsonResult<TUser> edit(@RequestBody @Valid UserCrateVO userCrateVO){

        if(userCrateVO.getId()==null){
            TUser user = userService.getUserByUserName(userCrateVO.getUserName());
            if(user!=null){
                return  new JsonResult<>(2,"用户已存在");
            }
            if( StringUtils.isBlank(userCrateVO.getPassword()) ){
                return  new JsonResult<>(3,"密码不能为空");
            }
        }
        if(StringUtils.isBlank(userCrateVO.getBirthDay())){
            userCrateVO.setBirthDay(null);
        }
        TUser user=new TUser();
        BeanUtils.copyProperties(userCrateVO,user);
        if (userCrateVO.getId() == null) {
            String encodePwd = pwdToolsServiceIpml.encrypt(userCrateVO.getPassword(),"123");
            user.setPassword(encodePwd);
            user.setUserUuid(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setLastActiveTime(new Date());
            user.setDeleted(false);
            userService.insertByFilter(user);
        } else {
            if (!StringUtils.isBlank(userCrateVO.getPassword())) {
                String encodePwd = pwdToolsServiceIpml.encrypt(userCrateVO.getPassword(),"123");
                user.setPassword(encodePwd);
            }
            user.setModifyTime(new Date());
            userService.updateByIdFilter(user);
        }
        return JsonResult.ok(user);

    }


@RequestMapping("/delete/{id}")
    public JsonResult delete(@PathVariable Integer id){
    TUser tuser = userService.getUserById(id);
         tuser.setDeleted(true) ;
         userService.updateByIdFilter(tuser);
         return JsonResult.ok();

}
    @RequestMapping(value = "/selectByUserName", method = RequestMethod.POST)
    public JsonResult<List<KeyValue>> selectByUserName(@RequestBody String userName) {
        List<KeyValue> keyValues = userService.selectByUserName(userName);
        return JsonResult.ok(keyValues);
    }

    @RequestMapping(value = "/changeStatus/{id}", method = RequestMethod.POST)
    public JsonResult<Integer> changeStatus(@PathVariable Integer id) {
        TUser user = userService.getUserById(id);
        UserStatusEnum userStatusEnum = UserStatusEnum.fromCode(user.getStatus());
        Integer newStatus = userStatusEnum == UserStatusEnum.Enable ? UserStatusEnum.Disable.getCode() : UserStatusEnum.Enable.getCode();
        user.setStatus(newStatus);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);
        return JsonResult.ok(newStatus);
    }


}
